import React from 'react';
import { Space } from 'antd';
import { HomeOutlined } from '@ant-design/icons';
import type { BreadcrumbProps } from 'antd';
import type { Menu as MenuType } from '@/types/rbac';

/**
 * 菜单匹配结果
 */
export interface MenuMatchResult {
  menu: MenuType | null;
  ancestors: MenuType[];
  score: number;
}

/**
 * 面包屑生成器类
 * 负责根据菜单树和当前路径生成面包屑导航
 */
export class BreadcrumbGenerator {
  private menuCache = new Map<string, MenuType[]>();
  private pathCache = new Map<string, MenuMatchResult>();

  /**
   * 清空缓存
   */
  clearCache(): void {
    this.menuCache.clear();
    this.pathCache.clear();
  }

  /**
   * 生成面包屑项列表
   */
  generateBreadcrumbItems(
    menus: MenuType[],
    pathname: string,
    options: {
      includeHome?: boolean;
      homePath?: string;
      homeTitle?: string;
    } = {}
  ): NonNullable<BreadcrumbProps['items']> {
    const { includeHome = true, homePath = '/dashboard', homeTitle = '首页' } = options;

    // 使用缓存键
    const cacheKey = `${JSON.stringify(menus)}-${pathname}`;
    
    let matchResult = this.pathCache.get(cacheKey);
    if (!matchResult) {
      matchResult = this.findBestMatch(menus, pathname);
      this.pathCache.set(cacheKey, matchResult);
    }

    const items: NonNullable<BreadcrumbProps['items']> = [];

    // 检查是否匹配到首页菜单
    const isHomePage = matchResult.menu && this.isHomeMenu(matchResult.menu, homePath);

    if (matchResult.menu) {
      // 如果匹配到首页菜单，只显示首页
      if (isHomePage) {
        const currentTitle = this.getMenuTitle(matchResult.menu);
        items.push(this.createBreadcrumbItem('current', currentTitle, undefined, React.createElement(HomeOutlined)));
      } else {
        // 非首页菜单：添加祖先链 + 当前菜单
        matchResult.ancestors.forEach((ancestor, index) => {
          const key = `ancestor-${index}`;
          const title = this.getMenuTitle(ancestor);
          const href = this.getMenuPath(ancestor);
          items.push(this.createBreadcrumbItem(key, title, href));
        });

        // 添加当前菜单
        const currentTitle = this.getMenuTitle(matchResult.menu);
        items.push(this.createBreadcrumbItem('current', currentTitle));
      }
    } else {
      // 没有匹配到任何菜单时的处理
      if (includeHome && pathname !== homePath) {
        // 只有在不是首页路径时才添加首页链接
        items.push(this.createBreadcrumbItem('home', homeTitle, homePath, React.createElement(HomeOutlined)));
      }

      // Fallback: 使用路径片段生成面包屑
      const pathSegments = pathname.split('/').filter(Boolean);
      if (pathSegments.length > 0) {
        pathSegments.forEach((segment, index) => {
          const key = `segment-${index}`;
          const title = this.formatPathSegment(segment);
          // 只有非最后一个片段才可点击
          const href = index < pathSegments.length - 1 
            ? '/' + pathSegments.slice(0, index + 1).join('/')
            : undefined;
          items.push(this.createBreadcrumbItem(key, title, href));
        });
      } else if (items.length === 0) {
        // 完全没有匹配且是根路径时，显示首页
        items.push(this.createBreadcrumbItem('fallback-home', homeTitle, undefined, React.createElement(HomeOutlined)));
      }
    }

    return items;
  }

  /**
   * 查找最佳匹配的菜单项
   */
  private findBestMatch(menus: MenuType[], pathname: string): MenuMatchResult {
    // 生成候选路径（支持路由别名）
    const candidatePaths = this.generateCandidatePaths(pathname);
    
    let bestMatch: MenuMatchResult = {
      menu: null,
      ancestors: [],
      score: -1
    };

    // 深度优先搜索，查找最佳匹配
    const dfs = (nodes: MenuType[], ancestors: MenuType[] = []): void => {
      for (const node of nodes) {
        const menuPath = this.getMenuPath(node);
        if (!menuPath) continue;

        // 计算匹配分数
        const score = this.calculateMatchScore(menuPath, candidatePaths);
        
        if (score > bestMatch.score) {
          // 对于首页菜单，确保它作为一级菜单处理
          const isHome = this.isHomeMenu(node, '/dashboard');
          const adjustedAncestors = isHome ? [] : [...ancestors];
          
          bestMatch = {
            menu: node,
            ancestors: adjustedAncestors,
            score
          };
        }

        // 递归搜索子菜单
        const children = this.getMenuChildren(node);
        if (children && children.length > 0) {
          // 对于首页菜单，不传递自身作为祖先
          const isHome = this.isHomeMenu(node, '/dashboard');
          const nextAncestors = isHome ? ancestors : [...ancestors, node];
          dfs(children, nextAncestors);
        }
      }
    };

    dfs(menus);
    return bestMatch;
  }

  /**
   * 生成候选路径（处理路由别名）
   */
  private generateCandidatePaths(pathname: string): string[] {
    const paths = [pathname];
    
    // 处理 /system 前缀的路由别名
    if (pathname.startsWith('/system')) {
      paths.push(pathname.replace(/^\/system/, ''));
    } else {
      paths.push(`/system${pathname}`);
    }

    return paths;
  }

  /**
   * 计算路径匹配分数
   */
  private calculateMatchScore(menuPath: string, candidatePaths: string[]): number {
    let maxScore = -1;

    for (const candidatePath of candidatePaths) {
      if (candidatePath === menuPath) {
        // 完全匹配，给予最高分数
        maxScore = Math.max(maxScore, menuPath.length + 10000);
      } else if (candidatePath.startsWith(menuPath + '/')) {
        // 前缀匹配，分数为路径长度
        maxScore = Math.max(maxScore, menuPath.length);
      }
    }

    return maxScore;
  }

  /**
   * 创建面包屑项
   */
  private createBreadcrumbItem(
    key: string,
    title: string,
    href?: string,
    icon?: React.ReactNode
  ): NonNullable<BreadcrumbProps['items']>[0] {
    return {
      key,
      href,
      title: React.createElement(Space, {}, icon, React.createElement('span', {}, title))
    };
  }

  /**
   * 获取菜单标题
   */
  private getMenuTitle(menu: MenuType): string {
    const menuAny = menu as any;
    return menuAny.name || menuAny.label || menuAny.code || '未知菜单';
  }

  /**
   * 获取菜单路径
   */
  private getMenuPath(menu: MenuType): string {
    const menuAny = menu as any;
    return menuAny.path || '';
  }

  /**
   * 获取菜单子项
   */
  private getMenuChildren(menu: MenuType): MenuType[] {
    const menuAny = menu as any;
    return menuAny.children || [];
  }

  /**
   * 判断是否为首页菜单
   */
  private isHomeMenu(menu: MenuType, homePath: string): boolean {
    const menuPath = this.getMenuPath(menu);
    const menuCode = (menu as any).code || '';
    
    // 检查路径匹配
    if (menuPath === homePath || menuPath === '/dashboard' || menuPath === '/platform/dashboard') {
      return true;
    }
    
    // 检查菜单代码
    if (menuCode.toLowerCase() === 'dashboard' || menuCode.toLowerCase() === 'home') {
      return true;
    }
    
    return false;
  }

  /**
   * 格式化路径片段（用于 fallback）
   */
  private formatPathSegment(segment: string): string {
    // 简单的格式化：首字母大写，替换连字符
    return segment
      .split('-')
      .map(word => word.charAt(0).toUpperCase() + word.slice(1))
      .join(' ');
  }
}

/**
 * 全局面包屑生成器实例
 */
export const breadcrumbGenerator = new BreadcrumbGenerator();

/**
 * 便捷函数：生成面包屑项
 */
export const generateBreadcrumbItems = (
  menus: MenuType[],
  pathname: string,
  options?: Parameters<BreadcrumbGenerator['generateBreadcrumbItems']>[2]
): NonNullable<BreadcrumbProps['items']> => {
  return breadcrumbGenerator.generateBreadcrumbItems(menus, pathname, options);
};

/**
 * 便捷函数：清空面包屑缓存
 */
export const clearBreadcrumbCache = (): void => {
  breadcrumbGenerator.clearCache();
};